package com.licq.ldoc.writer.visitor.example.exampler;

import java.util.Collection;
import java.util.HashSet;

import com.licq.ldoc.domain.Element;
import com.licq.ldoc.domain.ElementType;
import com.licq.ldoc.domain.ElementType.ElementTypeDecorator;
import com.licq.ldoc.utils.ClassUtils;
import com.licq.ldoc.writer.visitor.example.ExampleVisitor;
import com.licq.ldoc.writer.visitor.example.Exampler;
import com.lowagie.text.BadElementException;

/**
 * 
 * @author liujian
 *
 */
public class WrapperAttributeElementExampler extends Exampler {
	
	private org.dom4j.Element domElement;

	private Object object;

	private Element element;

	public WrapperAttributeElementExampler(org.dom4j.Element domElement,
			Object object, Element element) {
		this.domElement = domElement;
		this.object = object;
		this.element = element;
	}

	@Override
	public void create() throws BadElementException {
		String property = element.getName();
		Object propertyValue = getPropertyValue(object, property);
		if (propertyValue == null && element.isRequired()) {
			propertyValue = mockPropertyValue();
		}
		if (propertyValue != null) {
			Object[] valueArray = null;
			if (propertyValue.getClass().isArray()) {
				valueArray = (Object[]) propertyValue;
			} else {
				valueArray = ((Collection<?>) propertyValue).toArray();
			}
			org.dom4j.Element ele = domElement.addElement(property);
			for (Object value : valueArray) {
				String innerClazzName = getInnerType().getClazz().getSimpleName();
				org.dom4j.Element innerEle = ele.addElement(innerClazzName);
				element.accept(new ExampleVisitor(innerEle, value));
			}
		}
	}

	@SuppressWarnings("unchecked")
	private Collection mockPropertyValue() {
		Collection collection = new HashSet();
		ElementType innerType = getInnerType();
		for (int i = 0; i < 2; i++) {
			collection.add(ClassUtils.newInstance(innerType.getClazz()));
		}
		return collection;
	}

	private ElementType getInnerType() {
		return ((ElementTypeDecorator) element.getType()).getElementType();
	}

}
